package com.turman.builibrary.banner.core;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import java.lang.reflect.Field;

/**
 * 自动翻页viewpager
 *
 * @author buobao
 * @since 2024/3/18 11:03
 */
public class BViewPager extends ViewPager {
    //轮播间隔
    private int mInterval = 3000;
    //是否自动轮播
    private boolean mAutoPlay = true;
    //当前是否正在轮播
    private boolean isLayout;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            next();
            mHandler.postDelayed(this, mInterval);
        }
    };

    public BViewPager(@NonNull Context context) {
        this(context, null);
    }

    public BViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        isLayout = true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                start();
                break;
            default:
                stop();
                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (isLayout && getAdapter() != null && getAdapter().getCount() > 0) {
            try {
                //修复 使用recyclerView和ViewPager bug
                Field mScroller = ViewPager.class.getDeclaredField("mFirstLayout");
                mScroller.setAccessible(true);
                mScroller.set(this,false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        start();
    }

    @Override
    protected void onDetachedFromWindow() {
        if (((Activity)getContext()).isFinishing()) {
            super.onDetachedFromWindow();
        }
        stop();
    }

    private void start() {
        mHandler.removeCallbacksAndMessages(null);
        if (mAutoPlay) {
            mHandler.postDelayed(mRunnable, mInterval);
        }
    }

    private void init() {
        if (mAutoPlay) {
            mHandler.postDelayed(mRunnable, mInterval);
        }
    }

    public void stop() {
        mHandler.removeCallbacksAndMessages(null);
    }

    public void setAutoPlay(boolean mAutoPlay) {
        this.mAutoPlay = mAutoPlay;
        if (!mAutoPlay) {
            mHandler.removeCallbacks(mRunnable);
        }
    }

    public void setInterval(int interval) {
        this.mInterval = interval;
    }

    /**
    * 设置滚动速度
    * @author buobao
    * @since 2024/3/18 17:34
    */
    public void setScrollDuration(int duration) {
        try{
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);
            scrollerField.set(this, new BBannerScroller(getContext(),duration));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下一个显示位置
     *
     * @author buobao
     * @since 2024/3/18 13:17
     */
    private int next() {
        int nextPosition = -1;
        if (getAdapter() == null || getAdapter().getCount() <= 1) {
            stop();
            return nextPosition;
        }
        nextPosition = getCurrentItem() + 1;
        if (nextPosition >= getAdapter().getCount()) {
            //获取第一个item的索引
            nextPosition = ((BBannerAdapter) getAdapter()).getFirstItem();
        }
        setCurrentItem(nextPosition);
        return nextPosition;
    }
}




















